package com.kaishengit.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kaishengit.entity.User;
import com.kaishengit.service.loginService;




public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/views/index.jsp").forward(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String name=request.getParameter("name");
		String pwd=request.getParameter("password");
		if(name==null||"".equals(name)||pwd==null||"".equals(pwd)){
			response.sendRedirect("login.jspx?code=1002");
			return;
		}
		loginService service=new loginService();
		User user=service.findByName(name);
		
		if(user!=null&& user.getPassword().equals(pwd)){
			HttpSession session= request.getSession();
			session.setAttribute("user", user);
			String where = (String) session.getAttribute("where");
			if(where != null){
				session.removeAttribute("where");
				response.sendRedirect(where);
				return;
			}else{
				response.sendRedirect("project.jspx");
				return;
			}
			
		}else{
			response.sendRedirect("login.jspx?code=1001");
		}
	}	
}
